//
//  WSGPlayerKillingFieldCell.m
//  oneDollar
//
//  Created by Laki on 16/6/20.
//  Copyright © 2016年 com.Laki.corder. All rights reserved.
//

#import "WSGPlayerKillingFieldCell.h"
#import "WSGPlayerItem.h"

#import <UIImageView+WebCache.h>

@interface WSGPlayerKillingFieldCell()
/** 图片*/
@property (weak, nonatomic) IBOutlet UIImageView *productPicLinkImageView;
/** 名称*/
@property (weak, nonatomic) IBOutlet UILabel *productNameLabel;
/** 时长*/
@property (weak, nonatomic) IBOutlet UILabel *leftSecondsLabel;
/** 参与人数*/
@property (weak, nonatomic) IBOutlet UILabel *participantsLabel;
/** 定时器*/
@property (nonatomic,weak) NSTimer *timer;
@end

@implementation WSGPlayerKillingFieldCell

/*
 * 设置数据
 */
- (void)setItem:(WSGPlayerItem *)item{
    // 保存属性
    _item = item;

    // 设置图片
    [self.productPicLinkImageView sd_setImageWithURL:[NSURL URLWithString:item.productPicLink] placeholderImage:[UIImage imageNamed:@"Circle_BackgroundBigImage"]];
    
    // 设置名称
    self.productNameLabel.text = item.productName;
    
    // 进行分秒换算
    NSInteger minute = [item.leftSeconds intValue] / 60;
    NSInteger seconds = [item.leftSeconds intValue] % 60;
    
    //设置
    self.leftSecondsLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",minute,seconds];
    
    // 判断有没有人参与
    if ([item.participants isEqualToString:@"0"]) {
        self.participantsLabel.text = @"五折商品等你来拿";
    }else{
        // 创建一个富文本字符串
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"已有%02zd人参与",[item.participants intValue]]];

        // 设置参与人数的颜色
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(2, 2)];
        
        // 赋值
        self.participantsLabel.attributedText = str;
    }

    // 避免重复创建添加定时器
    if (self.timer == nil) {
        // 创建定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reloadTimer) userInfo:Nil repeats:YES];
        // 添加到当前主循环RunLoop中
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

/*
 * 刷新时间
 */
- (void)reloadTimer{
    static NSInteger leftSeconds = 0;

    // 判断时间是否归零
    if ([_item.leftSeconds intValue] == 0) {
        leftSeconds = 119;
        self.participantsLabel.text = @"五折商品等你来拿";
    }else{
        leftSeconds = [_item.leftSeconds intValue] - 1;
    }
    
    // 赋值
    _item.leftSeconds = [NSString stringWithFormat:@"%zd",leftSeconds];
    
    // 进行分秒换算
    NSInteger minute = [_item.leftSeconds intValue] / 60;
    NSInteger seconds = [_item.leftSeconds intValue] % 60;
    
    //设置
    self.leftSecondsLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",minute,seconds];
}

/*
 * 销毁定时器
 */
-(void)dealloc{
    // 销毁定时器
    [self.timer invalidate];
    
    // 指针清空
    self.timer = nil;
}
@end
